<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-invoice">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div class="create-invoice-inner">
      <div style="margin-bottom: 16px;">
        <Title title="申请信息" style="margin-bottom: 16px;" />
        <div class="invoice-abandon-form">
          <el-form ref="abandonFormRef" :rules="rules" :model="paramsObj" :label-position="formAlign" class="lineHeight32" label-width="90px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请人" prop="proposerId">
                  <selectWithUserLoad
                    ref="proposerRef"
                    v-model="paramsObj.proposerObj"
                    :default-list="paramsObj.proposerId && paramsObj.proposer?[{id: paramsObj.proposerId, userName: paramsObj.proposer}] : []"
                    :multiple="false"
                    :value-type="'object'"
                    :show-check-user="true"
                    key-name="id"
                    class="width240"
                    label-name="userName"
                    filterable
                    clearable
                    @change="proposerChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请部门" prop="deptId">
                  <el-cascader
                    v-model="paramsObj.deptId"
                    :show-all-levels="false"
                    :options="deptTreeList"
                    :props="{
                      emitPath:false,
                      value: 'id',
                      label: 'name',
                      checkStrictly: true,
                      multiple: false,
                    }"
                    class="width240"
                    placeholder="请选择申请部门"
                    size="small"
                    clearable
                    filterable
                  >
                    <template slot-scope="{ data }">
                      <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                        <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                        <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                      </el-tooltip>
                      <span v-else>{{ data.name }}</span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="作废说明" prop="abandonRemark">
                  <el-input v-model="paramsObj.abandonRemark" :maxlength="500" class="width240" resize="none" placeholder="请输入作废说明" type="textarea" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="附件" prop="attachment">
                  <upAttachment
                    ref="uploadImg"
                    :import-api="'/common/file/upload'"
                    :hide-confirm="true"
                    :is-disabled="false"
                    :file-list="paramsObj.attachment"
                    :limit="10"
                    btn-text="上传附件"
                    @upProgress="upProgress"
                    @complateSetData="complateSetData"
                    @removeFileList="removeFileList"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div style="position: relative;">
        <InvoiceAndContract
          ref="InvoiceSelect"
          :related-contract-style="{position: 'absolute',top: '-7px',right: '0'}"
          :type="2"
          :is-abandon="true"
          title="需要作废的发票"
          show-empty />
      </div>
      <audit-process
        ref="auditProcessRef"
        :loading="btnLoading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :default-aduitor-list="[paramsObj.proposerObj]"

        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="toSubmit(SUBMITTYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination>
        <div class="center">
          <el-button v-if="(!remodifyId && !reapplyId) || createNew" :loading="btnLoading" type="primary" size="small" plain class="plain" @click="toSubmit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
          <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
          <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
// components
import Title from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import filterCascader from '@/components/Common/filterCascader';
import upAttachment from '@/components/Common/upAttachment/index';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import { isContained } from '@/utils/tools';

// api
import { editAbandon, createAbandon, formSubmitAbandon, getAbandonDetail } from '@/api/invoiceAbandon';
import { getDepartmentAll } from '@/api/config';
import { processManagementDetail } from '@/api/legal';
// import { formSubmit } from '@/api/signUp';
// util
import { SUBMITTYPE } from '@/utils/const/cost';
import { createAuditStructure } from '@/utils/aduitor';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, selectWithUserLoad, filterCascader, upAttachment, InvoiceAndContract, AuditProcess, explanation },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      SUBMITTYPE,
      createLoading: false,
      btnLoading: false,
      isEdit: false,
      paramsObj: {
        proposerObj: {},
        proposer: '',
        proposerId: '',
        deptId: '',
        abandonRemark: '',
        attachment: [],
        invoiceList: []
      },
      invoiceId: '',
      deptTreeList: [],
      rules: {
        'proposerId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'abandonRemark': [{ required: true, message: '请输入作废说明', trigger: 'blur' }]
      },
      // 流程信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      processDetail: null,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    this.queryDeptTreeList();
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.invoiceId = Number(this.$route.params.id) || '';
    this.remodifyId = this.$route.query.remodifyId; // 修改
    this.reapplyId = this.$route.query.reapplyId; // 重新申请
    if (this.invoiceId) {
      this.isEdit = true;
      this.getDetail();
      this.reapplyId && this.getExplanation();
    } else {
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        this.paramsObj.deptId = this.getFirstDepartment(this.userInfo.departmentAry);
      }
      this.paramsObj.proposerId = this.userInfo.id;
      this.paramsObj.proposer = this.userInfo.userName;
      this.paramsObj.proposerObj = {
        id: this.paramsObj.proposerId,
        userName: this.paramsObj.proposer
      };
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    getDetail() {
      getAbandonDetail({ id: this.invoiceId }).then(res => {
        if (res.code === 200) {
          this.paramsObj = res.data;
          if (res.data.invoiceList) {
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceList);
          }
          if (this.paramsObj.proposerId) {
            this.paramsObj.proposerObj = {
              id: this.paramsObj.proposerId,
              userName: this.paramsObj.proposer
            };
          }
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      });
    },
    toSubmit(submitType = SUBMITTYPE.SUBMIT, senders = []) {
      this.modifySenders = senders;// 存到mixins
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      const invoiceSelect = this.$refs.InvoiceSelect;
      if (invoiceSelect && invoiceSelect.selectData) {
        params.invoiceList = invoiceSelect.selectData;
      }
      params.submitType = submitType;
      if (submitType !== SUBMITTYPE.DRAFT && this.reapplyId && !this.createNew) { // 重新提交
        params.submitType = SUBMITTYPE.RESUBMIT;
      }
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.auditInfo = this.auditInfo;
      if (this.createNew) {
        delete params.id;
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        params.id = this.invoiceId;
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      if (this.isEdit && !this.createNew) {
        params.id = this.invoiceId;
        this.$confirm('请确认是否发起审批', '', {
          confirmButtonText: '确定', type: 'warning', showClose: false,
          center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
        }).then(() => {
          this.handleModifyData(params);
          this.edit(params);
        });
      } else {
        const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
        this.$confirm(msg, '', {
          confirmButtonText: '确定', type: 'warning', showClose: false,
          center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
        }).then(() => {
          this.create(params);
        });
      }
    },
    // 流程相关 start
    openDrawer() { // 流程弹窗
      this.$refs.abandonFormRef.validate(valid => {
        if (valid) {
          const invoiceList = this.$refs.InvoiceSelect.selectData;
          if (!invoiceList || invoiceList.length === 0) {
            this.$message.error('请选择需要作废的发票');
            return;
          }
          this.getProcessDetail();
        } else {
          this.$message.warning('请检查信息是否填写完整');
        }
      });
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    getProcessDetail(isRefresh) {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      const invoiceSelect = this.$refs.InvoiceSelect;
      if (invoiceSelect && invoiceSelect.selectData) {
        params.invoiceList = invoiceSelect.selectData;
      }
      params.type = 16; // 流程类型，发票作废
      this.btnLoading = true;
      // formSubmit formSubmitAbandon
      formSubmitAbandon(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcessRef'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = {
              id: this.paramsObj.proposerId,
              userName: this.paramsObj.proposer
            };
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcessRef'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: 16 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    // 流程相关 end
    create(params) {
      this.btnLoading = true;
      createAbandon(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'invoiceAbandonDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        this.btnLoading = false;
      });
    },
    edit(params) {
      this.btnLoading = true;
      editAbandon(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.processId) {
            this.$router.push({
              name: 'invoiceAbandonDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'invoiceAbandonDetail', params: {}, query: { id: this.invoiceId, processId: this.remodifyId }});
        }
        this.btnLoading = false;
      });
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.paramsObj.attachment.push(fileList);
    },
    upLoadError() {
      this.createLoading = false;
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    toBack() {
      this.$router.push({
        name: 'invoiceAbandon'
      });
    },
    proposerChange(data) {
      this.paramsObj.proposerId = data.id;
      this.paramsObj.proposer = data.userName;
    },
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.create-invoice {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 80px);
  .create-invoice-inner {
    padding: 24px 24px 50px 24px;
  }
}
.plain {
  background-color: #fff;
}
.width240 {
  width: 240px;
}
</style>
